<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../../css/header.css" />
		<link rel="stylesheet" type="text/css" href="../../css/chat.css" />
		<link rel="stylesheet" href="../../fonticon/iconfont.css">
		<script src="../../fonticon/iconfont.js"></script>
		<style>
			html,
			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
			}
			.head-img{
				border-radius: 5px;
			}
		</style>
	</head>

	<body contextmenu="return false;">
		<header class="mui-bar mui-bar-nav title" style="position: fixed;">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left title-color" id="btn_goto_chat"></a>
			<span class="mui-title title-color" style="text-align: left; margin-top: 2px;" id="chatting-nickname"></span>
		</header>

		<div id="msg-outter" class="mui-content">
			<div id='msg'>

			</div>
		</div>

		<footer>
			<label class="footer-left">
				<span class="iconfont" style="font-size: 28px;line-height: 50px;" id="btn_change_recording">&#xe618;</span>
				<span class="iconfont" style="font-size: 28px;line-height: 50px; display: none;" id="btn_change_keybord">&#xe7db;</span>
			</label>
			<div class="footer-center">
				<textarea id='input_message' type="text" class='input-text'></textarea>
				<button class="mui-btn" style="width: 100%; padding: 7px; font-size: 16px; display: none; border-radius: 5px;" id="btn_recording">按住
					说话</button>
			</div>
			<label for="" class="footer-right">
				<span class="iconfont" style="font-size: 30px;line-height: 50px;" id="btn_smile">&#xe673;</span>
				<span class="iconfont" style="font-size: 29px;line-height: 50px;" id="btn_add_icon">&#xe635;</span>
				<button type="button" class="mui-btn mui-btn-green" id="btn_send" style="margin-top: 9px; display: none;">发送</button>
			</label>
		</footer>

		<script src="../../js/mui.min.js"></script>
		<script type="application/javascript" src="../../js/app.js"></script>
		<script type="application/javascript" src="../../js/api/friendapi.js"></script>
		<script type="application/javascript" src="../../js/socket/messageData.js"></script>
		<script type="application/javascript" src="../../js/db/db.js"></script>
		<script type="application/javascript" src="../../js/db/frienddb.js"></script>
		<script type="application/javascript" src="../../js/db/chatmessagedb.js"></script>
		<script type="application/javascript" src="../../js/db/chatsnapshotmessagedb.js"></script>
		<script type="text/javascript">
			// 创建命名空间，只需要把自己的代码，写进入，那么外部就无法访问
			//			(function($, doc){
			mui.init({
				gestureConfig: {
					longtap: true,
					hold: true,
					release: true
				}
			});
			// 获取上一个页面传入的好友属性值
			let friendUserId;
			let friendNickname;
			let friendThumHeadPortrait;
			let friendAccount;
			mui.plusReady(function() {
				// 获取我自己的用户信息					
				const user = app.getCacheUser();
				// 获取聊天页面webview
				let currentWebview = plus.webview.currentWebview();
				currentWebview.addEventListener("show", function() {
					console.log('chatting show')
					// 渲染初始化的聊天记录HTML
					initChatHistory(() => {
						// 为用户头像批量绑定点击事件
						bindHeadImgEvent();
						// 设置聊天记录进入页面的时候自动滚动到最后一条
						let areaMsgList = document.getElementById("msg");
						areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
					});
				});

				// 设置聊天页面的软键盘样式
				currentWebview.setStyle({
					softinputMode: "adjustResize"
				});
				//关闭等待框
				plus.nativeUI.closeWaiting();
				//显示当前页面
				mui.currentWebview.show();

				// 获取上一个页面传入的好友属性值
				friendUserId = currentWebview.friendUserId;
				friendNickname = currentWebview.friendNickname;
				friendThumHeadPortrait = currentWebview.friendThumHeadPortrait;
				friendAccount = currentWebview.friendAccount;

				// 标题改为朋友的昵称
				document.getElementById("chatting-nickname").innerHTML = friendNickname;

				// 初始化用户的聊天记录
				function initChatHistory(call) {
					let msg_list = document.getElementById("msg");
					let user = app.getCacheUser();
					let userId = user.id;
					let thumHeadPortrait = user.thumHeadPortrait;
					let params = {
						userId: userId,
						friendId: friendUserId
					}
					// console.log('初始化聊天记录');
					// console.log(JSON.stringify(params));
					chatmessagedb.select(params, (data) => {
						// console.log(JSON.stringify(data));
						let html = '';
						for (let i = 0; i < data.length; i++) {
							let chatHistory = data[i];
							if (chatHistory.is_myself == 1) {
								html += '<div class="me_lists">' +
									'<div class="header_img">' +
									'<img class="head-img" account="' + user.account + '" src="' + thumHeadPortrait +
									'" width="40px" height="40px" />' +
									'</div>' +
									'<div class="msg-wrapper left">' +
									'<p class="msg-right-green">' + chatHistory.message + '</p>' +
									'</div>' +
									'</div>';
							} else {
								html += '<div class="friend_lists">' +
									'<div class="header_img">' +
									'<img class="head-img" account="' + friendAccount + '" src="' + friendThumHeadPortrait +
									'" width="40px" height="40px" />' +
									'</div>' +
									'<div class="msg-wrapper right">' +
									'<p class="msg-left-white">' + chatHistory.message + '</p>' +
									'</div>' +
									'</div>';
							}
						}
						msg_list.innerHTML = html;
						if (typeof call === 'function') {
							call();
						}
					});
				}

				// ========== 返回聊天列表页面按钮 start ==========
				const btnGotoChat = document.getElementById("btn_goto_chat");
				btnGotoChat.addEventListener("tap", function() {
					currentWebview.close();
					const indexWebview = plus.webview.getWebviewById("index.html");
					indexWebview.evalJS("showChatPage(0)");
				});
				// ========== 返回聊天列表页面按钮 end ==========

				// ========== 语音切换按钮 start ==========
				const btnChangeRecording = document.getElementById("btn_change_recording");
				btnChangeRecording.addEventListener('tap', () => {
					btnChangeRecording.style.display = 'none';
					document.getElementById('input_message').style.display = 'none';
					document.getElementById('btn_recording').style.display = 'inline';
					document.getElementById("btn_change_keybord").style.display = 'inline';
				});
				// ========== 语音切换按钮 end ==========

				// ========== 键盘切换按钮 start ==========
				const btnChangeKeybord = document.getElementById("btn_change_keybord");
				btnChangeKeybord.addEventListener('tap', () => {
					btnChangeKeybord.style.display = 'none';
					document.getElementById('btn_recording').style.display = 'none';
					document.getElementById('input_message').style.display = 'inline';
					document.getElementById("btn_change_recording").style.display = 'inline';
				});
				// ========== 键盘切换按钮 end ==========


				// ========== 文本输入框 start ==========
				const inputMessage = document.getElementById("input_message");
				inputMessage.addEventListener("input", function() {
					const msg_text_val = inputMessage.value;
					if (msg_text_val.length > 0) {
						changeFooterDisplay('inline', 'none', '35px', '100px');
					} else {
						changeFooterDisplay('none', 'inline', '15px', '80px');
					}
				});

				function changeFooterDisplay(display_1, display_2, marginRight, width) {
					btnSend.style.display = display_1;
					btnAddIcon.style.display = display_2;
					let footerCenters = document.getElementsByClassName("footer-center");
					if (footerCenters) {
						for (let s of footerCenters) {
							s.style.marginRight = marginRight;
						}
					}
					let footerRights = document.getElementsByClassName("footer-right");
					if (footerRights) {
						for (let s of footerRights) {
							s.style.width = width;
						}
					}
				}
				// ========== 文本输入框 end ==========

				// ========== 录音按钮 start ==========
				const btnRecording = document.getElementById("btn_recording");
				let recorder = null;
				btnRecording.addEventListener('longtap', () => {
					console.log('录音按钮长按事件');
					if (plus.audio == undefined) {
						app.showToast(type, "请打开设备麦克风权限");
						return;
					}
					// 录音操作
					recorder = plus.audio.getRecorder();
					recorder.record({
						filename: "_doc/audio/"
					}, function(path) {
						path = '_doc/audio/1586179006765.amr';
						console.log('录音完成：' + path);
						plus.io.resolveLocalFileSystemURL(path, function(entry) {
							uploadVoice(path);
						}, function(e) {
							// outLine('读取录音文件错误：' + e.message);
						});
					}, function(e) {
						console.log("Audio record failed: " + e.message);
					});
				});
				btnRecording.addEventListener('release', () => {
					console.log('录音按钮离开事件');
					// 停止录音
					if (recorder) {
						recorder.stop();
						recorder = null;
					}
				});

				let player = null;

				function playerInit(path) {
					player = plus.audio.createPlayer(path);
					if (player == null) {
						return;
					}
					// player.setRoute(plus.audio.ROUTE_EARPIECE); // 切换到听筒线路
					player.setRoute(plus.audio.ROUTE_SPEAKER); // 切换到扬声器线路
					// 设置音频播放模式,"soloAmbient" - 中止其他声音播放，不能后台播放，静音后无声音；
					player.setSessionCategory('soloAmbient');
					// 设置音频播放的参数
					const styles = {
						stop: function() { // 音频停止事件
							player = null;
						}
					}
					player.setStyles(styles);
				}

				function addVoice(path, entry) {
					console.log("entry = " + entry.name)
					console.log("上传前的文件名：" + entry.name);
					playerInit(path);
					player = plus.audio.createPlayer(path);
					player.play();
					// uploadVoice(path);
				}

				function uploadVoice(path) {
					console.log("开始上传：")
					const uploadUrl = app.audioUploadUrl;
					var task = plus.uploader.createUpload(uploadUrl, {
							method: "POST"
						},
						function(t, status) { //上传完成
							if (status == 200) {
								var dataStr = JSON.stringify(t.responseText);
								console.log("发送成功：" + dataStr);
								let data = JSON.parse(t.responseText);
								if (data.code === 0) {
									const fileId = data.data.fileId;
									if (fileId) {
										let html = ``;
									}
								} else {
									app.showToast("发送失败：" + data.msg, "error");
								}
							} else {
								app.showToast("发送失败：" + status, "error");
							}
						}
					);
					task.addData("sendUserId", user.id);
					task.addData("receiveUserId", friendUserId);
					task.addData("fileName", path.substring(path.lastIndexOf("/") + 1));
					task.addFile(path, {
						key: "file"
					})
					task.start();
				}
				// ========== 录音按钮 end ==========

				// ========== 微笑按钮 start ==========
				const btnSmile = document.getElementById("btn_smile");
				btnSmile.addEventListener('tap', () => {
					console.log('微笑按钮点击事件')
				});
				// ========== 微笑按钮 end ==========

				// ========== 加号按钮 start ==========
				const btnAddIcon = document.getElementById("btn_add_icon");
				btnAddIcon.addEventListener('tap', () => {
					console.log('加号按钮点击事件')
				});
				// ========== 加号按钮 end ==========

				// ========== 发送按钮 start ==========
				const btnSend = document.getElementById("btn_send");
				btnSend.addEventListener("tap", function() {
					// 发送之前判断网络的状态
					let currentType = plus.networkinfo.getCurrentType();
					console.log("网络连接 currentType: " + currentType)
					if (currentType == 0 || currentType == 1) {
						app.showToast("请打开网络连接...", "error");
						return;
					}

					// 获取消息内容
					let messageValue = inputMessage.value;
					if (!messageValue) { // 判断消息内容，如果长度等于0，则return
						return;
					}
					// 保存聊天历史记录到本地数据库
					let msg = {
						createTime: app.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
						message: messageValue,
						status: 1,
						receiveUserId: friendUserId,
						sendUserId: user.id,
						type: 1,
						isMyself: 1
					}
					chatmessagedb.insert(msg, () => {
						// 清空消息文本框中的内容
						inputMessage.value = "";
						// 发送消息, 渲染消息的html到msg div之下
						renderSendMsg(user.thumHeadPortrait, user.account, messageValue);
						// 保存聊天快照记录到本地缓存
						insertChatSnapshot(msg, () => {
							// websocekt发送消息到服务器
							sendMessage(msg);
						});
					});
				});
				// ========== 发送按钮 end ==========

				// 保存聊天快照记录到本地缓存
				function insertChatSnapshot(msg, call) {
					msg.unread = 0;
					chatsnapshotmessagedb.insert(msg, call);
				}

				// 发送消息到服务器
				function sendMessage(msg) {
					// 构建messageData
					let md = messageData.create(messageData.type.CHAT, msg.message, msg.receiveUserId)
					// 调用websocket 发送消息到服务器
					let indexWebview = plus.webview.getWebviewById("index.html");
					indexWebview.evalJS('sendMessage(' + JSON.stringify(md) + ')');

					// 刷新消息列表
					let chatWebview = plus.webview.getWebviewById("chat.html");
					chatWebview.evalJS("loadingChatSnapshot()");
				}

				// 对当前的窗口监听resize事件
				window.addEventListener("resize", function() {
					resizeScreen();
					document.getElementById("msg-outter").style.paddingBottom = "50px";
				});

			});

			// 渲染接收到的消息
			function receiveMsg(msg) {
				let msgHtml = '<div class="friend_lists">' +
					'<div class="header_img">' +
					'<img class="head-img" account="' + friendAccount + '" src="' + friendThumHeadPortrait +
					'" width="40px" height="40px" />' +
					'</div>' +
					'<div class="msg-wrapper right">' +
					'<p class="msg-left-white">' + msg + '</p>' +
					'</div>' +
					'</div>';
				let msg_list = document.getElementById("msg");
				msg_list.insertAdjacentHTML("beforeend", msgHtml);
				// 为用户头像批量绑定点击事件
				bindHeadImgEvent();

				// 标记聊天信息已读，将快照未读消息条数修改为0
				updateMessageIsRead();
				// playReceiveMsgSound();
			}

			/**
			 * 标记聊天信息已读，将快照未读消息条数修改为0
			 * @param {Object} call 回调函数
			 */
			function updateMessageIsRead(call) {
				let userId = app.getUserId();
				let friendId = friendUserId;
				chatsnapshotmessagedb.select({
					userId,
					friendId
				}, (data) => {
					if (data && data[0].unread > 0) {
						let snapshotId = data[0].snapshotId;
						// 标记未读状态为已读
						chatsnapshotmessagedb.updateUnread({
							id: snapshotId,
							unread: 0
						}, () => {
							let params2 = {
								userId: userId,
								friendId: friendId,
								status: 0
							};
							chatmessagedb.updateStatus(params2)
						});
					}
				})
			}

			// 渲染发送消息
			function renderSendMsg(imgUrl, account, msg) {
				let html = '<div class="me_lists">' +
					'<div class="header_img">' +
					'<img class="head-img" account="' + account + '" src="' + imgUrl + '" width="40px" height="40px" />' +
					'</div>' +
					'<div class="msg-wrapper left">' +
					'<p class="msg-right-green">' + msg + '</p>' +
					'</div>' +
					'</div>';
				let msg_list = document.getElementById("msg");
				msg_list.insertAdjacentHTML("beforeend", html);
				// 为用户头像批量绑定点击事件
				bindHeadImgEvent();
				// playSendMsgSound();
			}

			// 播放发送消息的铃声
			function playSendMsgSound() {
				let audioPlayer = plus.audio.createPlayer("/mp3/send.mp3");
				audioPlayer.play();
			}

			// 播放接受消息的铃声
			function playReceiveMsgSound() {
				let audioPlayer = plus.audio.createPlayer("/mp3/di_didi.mp3");
				audioPlayer.play();
			}

			// 重新调整聊天窗口
			function resizeScreen() {
				let areaMsgList = document.getElementById("msg");
				// 设置聊天记录进入页面的时候自动滚动到最后一条
				areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
			};
			
			/**
			 * 为用户头像批量绑定点击事件
			 */
			function bindHeadImgEvent() {
				// 取消事件
				mui("#msg").off("tap", ".head-img")
				// 绑定事件
				mui("#msg").on("tap", ".head-img", function(e) {
					var account = this.getAttribute("account");
					e.stopPropagation();
					friendapi.getFriendByAccount({
						userId: app.getUserId(),
						account: account
					}, (data) => {
						frienddb.updateExcute(data.word, data, () => {
							// 打开聊天子页面
							mui.openWindow({
								url: "../discover/friend-detail.html",
								id: 'friend-detail.html', // 每个朋友的聊天页面都是唯一对应的
								extras: {
									requestFriend: {
										id: data.id,
										account: data.account,
										nickname: data.nickname,
										thumHeadPortrait: data.thumHeadPortrait,
										address: data.address,
										span_signature: data.signature,
										isFriend: true
									}
								}
							});
						})
					})
				})
			}

			//			}(mui, document));
		</script>
	</body>

</html>
